package com.tsingtree.config.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.IoUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class ImageConverter implements Converter<URL> {
    @Override
    public Class supportJavaTypeKey()
    {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey()
    {
        return CellDataTypeEnum.RICH_TEXT_STRING;
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<URL> context) {
        URL urlValue = context.getValue();
        InputStream inputStream = null;
        try {
            URLConnection uc = urlValue.openConnection();
            // 获取响应状态
            int statusCode = ((HttpURLConnection)uc).getResponseCode();
            if (statusCode == 200) {
                inputStream = urlValue.openStream();
            } else {
                return new WriteCellData<>("无法加载图片");
            }
            byte[] bytes = IoUtils.toByteArray(inputStream);
            WriteCellData<URL> cellData = new WriteCellData<>(bytes);
            cellData.setType(CellDataTypeEnum.RICH_TEXT_STRING);
            return cellData;
        } catch (IOException exception) {
            return new WriteCellData<>("无法加载图片");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
